/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.system.service.impl;


import com.koron.common.Tools;
import com.koron.common.bean.DepartmentTreeBean;
import com.koron.common.bean.SecretBean;
import com.koron.common.domain.DataBean;
import com.koron.common.generator.DefaultIdGenerator;
import com.koron.common.stub.Port;
import com.koron.system.bean.DistrictAndCorp;
import com.koron.system.domain.District;
import com.koron.system.domain.DistrictCorpRelation;
import com.koron.system.mapper.DistrictMapper;
import com.koron.system.mapper.InstitutionFileMapper;
import com.koron.system.service.api.DistrictService;
import com.koron.system.utils.BusinessCode;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.swan.bean.MessageBean;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@PropertySource({"classpath:system.properties"})
public class DistrictServiceImpl implements DistrictService {

    @Value("${app.orgCode}")
    private String orgCode;

    @Value("${app.defaultRole}")
    private String defaultRoleCode;   //默认角色code

    @Value("${app.appid}")
    private String appId;

    @Value("${app.secret}")
    private String secret;

    private final static  Logger logger = LoggerFactory.getLogger(DistrictServiceImpl.class);

    @Override
    public MessageBean<Integer> save(DistrictAndCorp districtAndCorp) {
        MessageBean<Integer> msg = new MessageBean<>();
        SessionFactory factory = new SessionFactory();
        try {
            DistrictMapper mapper = factory.getMapper(DistrictMapper.class);
            if (null == districtAndCorp || null == districtAndCorp.getDistrict()) {
                msg.setCode(BusinessCode.DISTRICT_EMPTY_SAVE_DATA.getCode());
                msg.setDescription(BusinessCode.DISTRICT_EMPTY_SAVE_DATA.getDescription());
                return msg;
            }

            District district = districtAndCorp.getDistrict();
            District enDistrict = null;
            if (StringUtils.isNotBlank(district.getId())) {
                enDistrict = queryOne(district.getId()).getData();
                if (null == enDistrict) {
                    msg.setCode(BusinessCode.DISTRICT_EMPTY_DATA_NOT_EXISIT.getCode());
                    msg.setDescription(BusinessCode.DISTRICT_EMPTY_DATA_NOT_EXISIT.getDescription());
                    return msg;
                }
            }

            if (StringUtils.isEmpty(district.getName())) {
                msg.setCode(BusinessCode.DISTRICT_EMPTY_NAME.getCode());
                msg.setDescription(BusinessCode.DISTRICT_EMPTY_NAME.getDescription());
                return msg;
            }
            List<DistrictCorpRelation> addRelationList = new ArrayList<>();
            StringBuilder decription = new StringBuilder();
            if (null != districtAndCorp.getDistrictCorpRelationList() && districtAndCorp.getDistrictCorpRelationList().size() > 0) {
                List<DistrictCorpRelation> relationList = districtAndCorp.getDistrictCorpRelationList();
                for (DistrictCorpRelation relation : relationList) {
                    if (StringUtils.isNotEmpty(relation.getCorpCode())) {
                        Port port = getPort();
                        List<DepartmentTreeBean> departmentTreeBeans = port.depttree(orgCode, relation.getCorpCode(), 0).getData();
                        if (null != departmentTreeBeans && departmentTreeBeans.size() > 0) {
                            DistrictCorpRelation en = mapper.queryDistrictCorpByCorpCode(relation.getCorpCode());
                            if (null == en) {
                                addRelationList.add(relation);
                            } else if (en.getDitrictCode().equals(enDistrict.getCode())) {
                                addRelationList.add(relation);
                            } else {
                                decription.append(departmentTreeBeans.get(0).getName()).append(",");
                            }
                        }
                    }
                }
            }
            if (StringUtils.isEmpty(district.getId())) {
                //新增操作
                String code = Tools.getCode32();
                district.setCode(code);
                district.setId(DefaultIdGenerator.getInstance().generateLongId());
                mapper.insertDistrict(district);
                for (DistrictCorpRelation corpRelation : addRelationList) {
                    corpRelation.setId(DefaultIdGenerator.getInstance().generateLongId());
                    corpRelation.setDitrictCode(code);
                }
                if (null != addRelationList && addRelationList.size() > 0) {
                    mapper.batchInsertDistrictCorp(addRelationList);
                }
            } else {
                if (StringUtils.isEmpty(district.getCode())) {
                    msg.setCode(BusinessCode.DISTRICT_EMPTY_CODE.getCode());
                    msg.setDescription(BusinessCode.DISTRICT_EMPTY_CODE.getDescription());
                    return msg;
                }
                mapper.updateDistrict(district);

                //片区制度需要相应更新
                List<DistrictCorpRelation> orgList = mapper.queryDistrictCorp(district.getCode(), null, null);
                if (orgList != null && !orgList.isEmpty()) {
                    List<String> delIdList = new ArrayList<>();
                    List<String> newIdList = addRelationList.stream().map(DistrictCorpRelation::getCorpCode).collect(Collectors.toList());
                    if (newIdList == null) {
                        List<String> orgIdList = orgList.stream().map(DistrictCorpRelation::getCorpCode).collect(Collectors.toList());
                        if (orgIdList != null && !orgIdList.isEmpty()) {
                            delIdList.addAll(orgIdList);
                        }
                    } else {
                        orgList.stream().forEach(districtCorpRelation -> {
                            if (!newIdList.contains(districtCorpRelation.getCorpCode())) {
                                delIdList.add(districtCorpRelation.getCorpCode());
                            }
                        });
                    }
                    //逻辑删除片区相关的制度
                    if (delIdList != null && !delIdList.isEmpty()) {
                        InstitutionFileMapper institutionFileMapper = factory.getMapper(InstitutionFileMapper.class);
                        institutionFileMapper.deleteDistrictWithCorpCode(district.getCode(), delIdList);
                    }
                }
                //先删除之前的片区与水司之间的关联
                mapper.deleteDistrictCorp(district.getCode());
                for (DistrictCorpRelation corpRelation : addRelationList) {
                    corpRelation.setId(DefaultIdGenerator.getInstance().generateLongId());
                    corpRelation.setDitrictCode(district.getCode());
                }
                mapper.batchInsertDistrictCorp(addRelationList);
            }
            factory.close();
            msg.setCode(BusinessCode.SUCCESS.getCode());
            if (StringUtils.isEmpty(decription)) {
                msg.setDescription("保存成功");
            } else {
                msg.setDescription("保存成功,但是以下水司" + decription.toString() + "已经在其他片区下，被忽略，没有进行保存");
            }
            msg.setData(1);
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            if (null != factory)
                factory.close(false);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }finally {
            if (null != factory) {
                factory.close();
            }
        }
    }

    @Override
    public MessageBean<Integer> deleteDistrict(String id) {
        MessageBean<Integer> msg = new MessageBean<>();
        SessionFactory factory = null;
        try {
            factory = new SessionFactory();
            if (StringUtils.isEmpty(id)) {
                msg.setCode(BusinessCode.DISTRICT_EMPTY_CHANGE_DATA.getCode());
                msg.setDescription(BusinessCode.DISTRICT_EMPTY_CHANGE_DATA.getDescription());
                return msg;
            }
            District district = factory.getMapper(DistrictMapper.class).queryOneDistrict(id);
            if (null == district) {
               /* msg.setCode(BusinessCode.DISTRICT_EMPTY_DATA_NOT_EXISIT.getCode());
                msg.setDescription(BusinessCode.DISTRICT_EMPTY_DATA_NOT_EXISIT.getDescription());
                return msg;*/
                msg.setCode(BusinessCode.SUCCESS.getCode());
                msg.setDescription("删除成功");
                return msg;
            }
            /*List<DistrictCorpRelation> relationList = factory.getMapper(DistrictMapper.class).queryDistrictCorp(district.getCode(),
                    null, null);
            if (relationList.size() > 0) {
                msg.setCode(BusinessCode.DISTRICT_EXISIT_CORP.getCode());
                msg.setDescription(BusinessCode.DISTRICT_EXISIT_CORP.getDescription());
                return msg;
            }*/
            //片区制度需要相应更新
            List<DistrictCorpRelation> orgList = factory.getMapper(DistrictMapper.class).queryDistrictCorp(district.getCode(), null, null);
            if (orgList != null && !orgList.isEmpty()) {
                List<String> delIdList = new ArrayList<>();
                List<String> orgIdList = orgList.stream().map(DistrictCorpRelation::getCorpCode).collect(Collectors.toList());
                if (orgIdList != null && !orgIdList.isEmpty()) {
                    delIdList.addAll(orgIdList);
                }
                //逻辑删除片区相关的制度
                if (delIdList != null && !delIdList.isEmpty()) {
                    InstitutionFileMapper institutionFileMapper = factory.getMapper(InstitutionFileMapper.class);
                    institutionFileMapper.deleteDistrictWithCorpCode(district.getCode(), delIdList);
                }
            }
            factory.getMapper(DistrictMapper.class).deleteDistrictCorp(district.getCode());
            factory.getMapper(DistrictMapper.class).deleteDistrict(id);
            factory.close(true);
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription("删除成功");
            return msg;
            /*if (value > 0) {
                msg.setCode(BusinessCode.SUCCESS.getCode());
                msg.setDescription("删除成功");
                msg.setData(value);
                return msg;
            } else {
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("删除失败");
                return msg;
            }*/
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
        }
        if (factory != null) {
            factory.close(false);
        }
        return msg;
    }

    @Override
    public MessageBean<District> queryOne(String id) {
        MessageBean<District> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            if (StringUtils.isEmpty(id)) {
                msg.setCode(BusinessCode.DISTRICT_EMPTY_CHANGE_DATA.getCode());
                msg.setDescription(BusinessCode.DISTRICT_EMPTY_CHANGE_DATA.getDescription());
                return msg;
            }
            District district = factory.getMapper(DistrictMapper.class).queryOneDistrict(id);
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription("获取片区详情成功");
            msg.setData(district);
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<District> queryOneByCode(String code) {
        MessageBean<District> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            if (StringUtils.isEmpty(code)) {
                msg.setCode(BusinessCode.DISTRICT_EMPTY_CHANGE_DATA.getCode());
                msg.setDescription(BusinessCode.DISTRICT_EMPTY_CHANGE_DATA.getDescription());
                return msg;
            }
            District district = factory.getMapper(DistrictMapper.class).queryOneDistrictByCode(code);
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription("查询成功");
            msg.setData(district);
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<Integer> deleteDistrictCorp(List<String> idList) {
        MessageBean<Integer> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            if (null == idList || idList.size() <= 0) {
                msg.setCode(BusinessCode.DISTRICT_EMPTY_CHANGE_DATA.getCode());
                msg.setDescription(BusinessCode.DISTRICT_EMPTY_CHANGE_DATA.getDescription());
                return msg;
            }
            Integer value = factory.getMapper(DistrictMapper.class).batchDeleteDistrictCorp(idList);
            List<DistrictCorpRelation> list = factory.getMapper(DistrictMapper.class).batchQueryDistrictCorp(idList);
            if (list != null && !list.isEmpty()) {
                for (DistrictCorpRelation districtCorpRelation:list){
                    InstitutionFileMapper institutionFileMapper = factory.getMapper(InstitutionFileMapper.class);
                    List<String> delIdList=new ArrayList<>();
                    delIdList.add(districtCorpRelation.getCorpCode());
                    institutionFileMapper.deleteDistrictWithCorpCode(districtCorpRelation.getDitrictCode(), delIdList);
                }
            }
            if (value > 0) {
                msg.setCode(BusinessCode.SUCCESS.getCode());
                msg.setDescription("删除成功");
                msg.setData(value);
                return msg;
            } else {
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("删除失败");
                return msg;
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<DataBean<District>> queryAllDistrict(Integer start, Integer rows) {
        MessageBean<DataBean<District>> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            List<District> list = factory.getMapper(DistrictMapper.class).queryAllDistrict(start, rows);
            Integer totalNumber = factory.getMapper(DistrictMapper.class).countTotalDistrict();
            rows = rows == null ? totalNumber : (rows <= 0 ? 1 : rows);
            Integer totalPage = totalNumber > rows ? (totalNumber % rows == 0 ? totalNumber / rows : totalNumber / rows + 1) : 1;
            DataBean<District> dataBean = new DataBean<>();
            dataBean.setList(list);
            dataBean.setTotalNumber(totalNumber);
            dataBean.setTotalPage(totalPage);
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription("获取片区列表成功");
            msg.setData(dataBean);
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<DataBean<DistrictCorpRelation>> queryDistrictCorp(String ditrictCode, Integer start, Integer rows) {
        MessageBean<DataBean<DistrictCorpRelation>> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            List<DistrictCorpRelation> list = factory.getMapper(DistrictMapper.class).queryDistrictCorp(ditrictCode, start, rows);
            Integer totalNumber = factory.getMapper(DistrictMapper.class).countDistrictCorp(ditrictCode);
            rows = rows == null ? totalNumber : (rows <= 0 ? 1 : rows);
            Integer totalPage = totalNumber > rows ? (totalNumber % rows == 0 ? totalNumber / rows : totalNumber / rows + 1) : 1;
            DataBean<DistrictCorpRelation> dataBean = new DataBean<>();
            list.forEach(item -> getNames(item));
            dataBean.setList(list);
            dataBean.setTotalNumber(totalNumber);
            dataBean.setTotalPage(totalPage);
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription("获取片区下关联的水司列表成功");
            msg.setData(dataBean);
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    private void getNames(DistrictCorpRelation relation) {
        if (null != relation) {
            if (StringUtils.isNotEmpty(relation.getCorpCode())) {
                Port port = getPort();
                List<DepartmentTreeBean> departmentTreeBeans = port.depttree(orgCode, relation.getCorpCode(), 0).getData();
                relation.setCorpName((departmentTreeBeans == null || departmentTreeBeans.size() <= 0) ? null : departmentTreeBeans.get(0).getName());
            }
            if (StringUtils.isNotEmpty(relation.getDitrictCode())) {
                District district = queryOneByCode(relation.getDitrictCode()).getCode() == 0 ? queryOneByCode(relation.getDitrictCode()).getData() : null;
                if (null != district)
                    relation.setDitrictName(district.getName());
            }
        }
    }

    @Override
    public List<DistrictCorpRelation> queryAssociatedCorp(String ditrictCode) {
        try (SessionFactory factory = new SessionFactory()) {
            Integer start = null, rows = null;
            List<DistrictCorpRelation> relations = factory.getMapper(DistrictMapper.class).queryDistrictCorp(ditrictCode, start, rows);
            relations.forEach(item -> getNames(item));
            return relations;
        }
    }

    public Port getPort() {
        SecretBean secretBean = new SecretBean();
        secretBean.setAppid(appId);
        secretBean.setSecret(secret);
        return new Port(secretBean);
    }


}
